import logging as logger
from fastapi import HTTPException
from pydantic import ValidationError
from sqlmodel import select
from api.deps import SessionDep
from models.user_model import User
from schemas.user_schema import UserCreate
from core.security import SecurityUtils

async def get_user_by_username(*, session: SessionDep, username: str):
    "根据用户名获取用户信息"
    statement = select(User).where(User.username == username)
    result = await session.exec(statement)
    return result.first()
async def create_new_user(*, session: SessionDep, user: UserCreate):
    "创建新用户"
    try:
        # 密码验证
        if user.password!= user.verify_password:
            raise ValidationError("密码不一致")

        # 检查用户名是否已存在
        if await get_user_by_username(session=session, username=user.username):
            raise HTTPException(400, "用户名已存在")

        # 创建新用户对象
        new_user = User.model_validate(user)
        # 密码哈希处理
        hashed_password = SecurityUtils.get_password_hash(user.password)
        new_user.hashed_password = hashed_password
        # 添加新用户到数据库
        session.add(new_user)
        await session.commit()
        await session.refresh(new_user)

        # 返回新用户对象
        return new_user
    except Exception as e:
        # 记录错误信息
        logger.error(f"创建新用户失败：{e}")
        # 抛出异常，让上层代码处理错误
        raise HTTPException(500, f"创建新用户失败")
    
